/**
 * 
 */
package cn.com.libertymutual.sys.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cn.com.libertymutual.core.exception.CustomLangException;
import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.sys.bean.PrpRisk;
import cn.com.libertymutual.sys.bean.SysCodeNode;
import cn.com.libertymutual.sys.bean.SysCodeType;
import cn.com.libertymutual.sys.bean.SysMenu;
import cn.com.libertymutual.sys.bean.SysServiceInfo;
import cn.com.libertymutual.sys.dao.ISysMenuDao;
import cn.com.libertymutual.sys.service.api.IInitSharedMemory;
import cn.com.libertymutual.sys.service.api.IRiskService;
import cn.com.libertymutual.sys.service.api.ISysCodeNodeService;
import cn.com.libertymutual.sys.service.api.ISysCodeTypeService;
import cn.com.libertymutual.sys.service.api.ISysServiceInfoService;

/**
 * @author bob.kuang
 *
 */
@Service("initSharedMemory")
public class InitSharedMemoryImpl implements IInitSharedMemory {
	private Logger log = LoggerFactory.getLogger(getClass());
	@Resource
	RedisUtils redisUtils;
	@Resource
	ISysServiceInfoService sysServiceInfoService;
	@Resource
	ISysCodeTypeService codeTypeService;
	@Resource
	ISysCodeNodeService sysCodeNodeService;
	@Resource
	ISysMenuDao menuDao;
	@Resource
	IRiskService riskService;
	

	// @Autowired IBaseDao<SysMenu, Integer> menuDao1;

	/**
	 * 初始化 ServiceInfo
	 */
	@Override
	public void initData() {

		// redisUtils.deleteAllKey();
		this.initSysMenu();
		this.initServiceInfo();
		this.initCodeInto();

	}

	/**
	 * 初始化 ServiceInfo
	 */
	@Override
	public void initServiceInfo() {

		Iterable<SysServiceInfo> sysServiceInfoList = sysServiceInfoService
				.getsysServiceInfo();
		Map<String, SysServiceInfo> map = Maps.newHashMap();
		for (SysServiceInfo sysServiceInfo : sysServiceInfoList) {
			map.put(sysServiceInfo.getServiceName(), sysServiceInfo);
		}

		redisUtils.set(Constants.SYS_SERVICE_INFO, map);
		Map<String, SysServiceInfo> mm = redisUtils.get(Constants.SYS_SERVICE_INFO,Map.class);
		//mm.get("")
	}

	@Override
	public void initCodeInto() {
		// 获取code类型
		List<SysCodeType> codeTypeList = codeTypeService.listAll();
		Map<String, SysCodeType> codeTypeMap = Maps.newHashMap();
		
		if( codeTypeList != null ) {
			for (SysCodeType type : codeTypeList) {
				codeTypeMap.put(type.getCodeType(), type);
			}
		}

		// 用于存放map code信息的map
		Map<String, Map<String, SysCodeNode>> mapCodeMap = Maps.newHashMap();
		// 用户存放前台需要的List,内容是Map author:tracy.liao date:2016-4-25
		Map<String, List<SysCodeNode>> newCodeMap = Maps.newHashMap();

		// 通过code类型查询该类型下的code列表放入到map中
		if (null != codeTypeList) {
			List<PrpRisk> riskList = riskService.listAll();
			for (SysCodeType codeType : codeTypeList) {
				// 去掉地区信息
				if (Constants.CODE_AREASORT.equals(codeType.getCodeType())) {
					continue;
				}
				// 根据码表类别查询码表记录，是R还是B或者空 author:tracy.liao date:2016-4-25
				String type = codeType.getType();
				String key = codeType.getCodeType();

				List<SysCodeNode> codeNodeList = sysCodeNodeService
						.findCodeInfoForValid(codeType.getCodeType());

				Map<String, SysCodeNode> nodeMap = Maps.newHashMap();
				
				if( codeNodeList != null ) {
					for (SysCodeNode n : codeNodeList) {
						nodeMap.put(n.getCode(), n);
					}
					;
					mapCodeMap.put(codeType.getCodeType(), nodeMap);
				}

				List<SysCodeNode> newCodeNodeList = null;
				if (null != codeNodeList) {
					if ("R".equals(type)) {
						for (PrpRisk prpRisk : riskList) {
							List<SysCodeNode> riskCodeList = sysCodeNodeService
									.findCodeInfoByRiskCode(
											codeType.getCodeType(),
											prpRisk.getRiskCode(), nodeMap);
							key = prpRisk.getRiskCode() + "-"
									+ codeType.getCodeType();
							newCodeMap.put(key, riskCodeList);
						}

					} else if ("B".equals(type)) {
						for (SysCodeNode codeNode : codeNodeList) {
							if (null != codeNode.getCode()) {
								// 判断是否包含在Map中
								key = codeNode.getBranchCode() + "-"
										+ codeNode.getCodeType();
								if (newCodeMap.containsKey(key)) {
									newCodeNodeList = newCodeMap.get(key);
									newCodeNodeList.add(codeNode);
								} else {
									newCodeNodeList = Lists.newArrayList();
									newCodeNodeList.add(codeNode);
									newCodeMap.put(key, newCodeNodeList);
								}
							}
						}
					} else {
						newCodeMap.put(key, codeNodeList);
					}
				}
			}
		}
		redisUtils.set(Constants.lIMIT_MAP_CODE_TYPE, codeTypeMap);
		redisUtils.set(Constants.lIMIT_LIST_CODE_TYPE, codeTypeList);
		// 以list和map两种形式存储数据
		redisUtils.set(Constants.MAP_CODE, mapCodeMap);
		redisUtils.set(Constants.lIMIT_LIST_CODE, newCodeMap);
/*		System.out.println(mapCodeMap.get("BranchCode").get("5000")
				.getCodeCname());
		
		Map<String, Map<String, SysCodeNode>> m2 = (Map<String, Map<String, SysCodeNode>>) redisUtils
				.get(Constants.MAP_CODE);
		Map<String, Map<String, SysCodeNode>> m = (Map<String, Map<String, SysCodeNode>>) redisUtils
				.get(Constants.MAP_CODE);
		SysCodeNode s = m.get("BranchCode").get("5000");
		if (m.get("BranchCode").get("5000") instanceof SysCodeNode) {
			s = m.get("BranchCode").get("5000");

		} else {
			System.out.println(m.get("BranchCode").get("5000").getClass()
					.getClassLoader().toString());
			System.out.println(SysCodeNode.class.getClassLoader().toString());
		}
		System.out.println(m.get("BranchCode").get("5000"));*/
	}

	@Override
	public Map<String, SysMenu> initSysMenu() {
		/*
		 * String sql = "SELECT DISTINCT t1.menuid FROM tb_sys_role_menu t1 ";
		 * // List<Integer> menuIdList = Lists.newArrayList();//
		 * roleMenuDao.nativeQuery4Map(sql); //List<Integer> menuIdList =
		 * roleMenuDao.findRoleMenu( userInfo.getRoleId(), fmenuId == null ? -1
		 * : fmenuId ); List<Map<String, Object>> tt =
		 * menuDao1.nativeQuery4Map(sql);
		 */

		try {
			List<SysMenu> menuList = null;
			menuList = menuDao.findAll();

			Map<String, SysMenu> menuMap = Maps.newHashMap();
			for (SysMenu SysMenu : menuList) {
				// 只缓存状态为1的菜单
				if (Strings.isNullOrEmpty(SysMenu.getStatus())
						|| !"1".equals(SysMenu.getStatus())) {
					continue;
				}
				menuMap.put(String.valueOf(SysMenu.getMenuid()), SysMenu);
			}

			Map<String, List<Integer>> menuMapRel = Maps.newHashMap();
			List<Integer> menuMapList = null;
			for (SysMenu menu : menuList) {
				// 只缓存状态为1的菜单
				if (Strings.isNullOrEmpty(menu.getStatus())
						|| !"1".equals(menu.getStatus())) {
					continue;
				}
				String fid = String.valueOf(menu.getFmenuid());
				if (menuMapRel.containsKey(fid)) {
					menuMapList = menuMapRel.get(fid);

				} else {
					menuMapList = Lists.newArrayList();
					menuMapRel.put(fid, menuMapList);
				}
				menuMapList.add(menu.getMenuid());

			}
			redisUtils.set(Constants.MENU_REL_INFO_KEY, menuMapRel);
			redisUtils.set(Constants.MENU_INFO_KEY, menuMap);

			return menuMap;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			// 将捕获到的异常转换为自定义异常抛出
			throw new CustomLangException(e);
		}
	}


}
